package com.cloud.zuul.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
//@Component
public class ErrorFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "error";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        System.out.println("error...");
        // Zuul网关提供的上下文对象
        RequestContext context = RequestContext.getCurrentContext();

        // 终止请求往下执行
        context.setSendZuulResponse(false);
        // 状态码
        context.setResponseStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value());

        HttpServletResponse response = context.getResponse();

        // 自定义响应内容
        HashMap jsonMap = new HashMap() {{
            put("flag", true);
            put("statusCode", "500");
            put("message", "出现错误啦！");
        }};
        response.setContentType("application/json;charset=utf8");
        try {
            response.getWriter().write(new ObjectMapper().writeValueAsString(jsonMap));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
